<?php

declare(strict_types=1);

namespace DreamCat\ObjectOrm;

use Psr\Container\ContainerInterface;
use ReflectionProperty;

/**
 * -
 * @author vijay
 */
class Utils
{
    /**
     * 通过属性反射获取指定的注解对象
     * @param ReflectionProperty $reflectionProperty 属性反射
     * @param string $className 要的注解类名
     * @psalm-param class-string<T> $className
     * @psalm-return ?T 注解对象
     * @template T
     */
    public static function getAttrObj(ReflectionProperty $reflectionProperty, string $className): ?object
    {
        $attr = $reflectionProperty->getAttributes($className);
        if ($attr) {
            return $attr[0]->newInstance();
        } else {
            return null;
        }
    }

    /**
     * 从容器获取指定对象
     * @param ContainerInterface $container 容器
     * @param string $beanName 实例名
     * @param ?string $className 要的指名
     * @psalm-param class-string<T> $className
     * @psalm-return ?T 实例
     * @template T
     */
    public static function getObjectFromContainer(
        ContainerInterface $container,
        string $beanName,
        string $className = null
    ): mixed {
        if (!$container->has($beanName)) {
            return null;
        }
        $object = $container->get($beanName);
        if ($object && $className && !$object instanceof $className) {
            return null;
        }
        return $object;
    }
}

# end of file
